package startup

import (
	article1 "bbs-web/internal/events/article"
	"bbs-web/internal/ioc"
	"bbs-web/internal/repository"
	article5 "bbs-web/internal/repository/article"
	"bbs-web/internal/repository/cache"
	"bbs-web/internal/repository/dao"
	"bbs-web/internal/repository/dao/article_dao"
	use "bbs-web/internal/repository/user"
	"bbs-web/internal/service"
	article3 "bbs-web/internal/service/article"
	"bbs-web/internal/web"
	"bbs-web/internal/web/handler"
	"bbs-web/internal/web/jwtx"
	"github.com/gin-gonic/gin"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

func InitArticleWebServer(path string) *gin.Engine {
	config := ioc.InitConfig(path)
	db := ioc.InitDatabase(config)
	cmdable := ioc.InitRedis(config)
	InitSaramaClient := ioc.InitSaramaClient(config)
	SyncProducer := ioc.InitSyncProducer(InitSaramaClient)
	logger := ioc.InitLogger()
	articleCache := cache.NewArticleCache(cmdable)
	producer := article1.NewKafkaProducer(SyncProducer)
	iUserDao := dao.NewuserDao(db)
	articleDAO := article_dao.NewGormArticleDao(db)
	iUserRepo := use.NewUserRepo(iUserDao)
	interactiveDao := dao.NewInteractiveDao(db)
	redisInteractiveCache := cache.NewRedisInteractiveCache(cmdable)
	interactiveRepo := repository.NewInteractiveRepo(interactiveDao, redisInteractiveCache, logger)
	interactiveService := service.NewInteractiveService(interactiveRepo, redisInteractiveCache)
	articleRepository := article5.NewArticleRepository(articleDAO, articleCache, logger, iUserDao)
	iUserService := service.NewUserService(iUserRepo)
	icaptchaService := service.NewCaptchaService()
	captchaHandler := handler.NewCaptchaHandler(icaptchaService)
	jwtHandler := jwtx.NewRedisJwtHandler(cmdable)
	userHandler := handler.NewuserHandler(iUserService, icaptchaService, jwtHandler)
	iArticleService := article3.NewArticleService(articleRepository, logger, producer)
	articleHandler := handler.NewArticleHandler(iArticleService, logger, interactiveService)
	router := web.NewRouter(userHandler, captchaHandler, articleHandler)
	v := ioc.InitMiddleware(config, jwtHandler)
	engine := ioc.InitGin(router, v)
	return engine
}

func InitTestDB(cfg *ioc.Config) *gorm.DB {
	config := &gorm.Config{}
	db, err := gorm.Open(mysql.Open(cfg.Database.DSN), config)
	if err != nil {
		panic(err)
	}
	return db
}
